成品連結:Video Speed Controller、操作前程式碼、完成後程式碼
今天要做的東西與之前所做的播放器有點類似,也是要控制影片的播放速度。只不過之前是使用 input range 來做,而今天是使用一般的 div,所以我們要自行計算速率及畫面上的顯示。
要做的事情有幾項,在這裡先列出,等等再一一解決
div.speed 的位置div.speed-bar 的 height 屬性div.speed-bar 的 textContent
video 得播放速度(playbackRate)由於預期的效果是當滑鼠 hover 過 div.speed 時更改播放速度,故要將監聽事件綁在 div.speed 上
const speed = document.querySelector('.speed');
const speedBar = document.querySelector('.speed-bar');
const video = document.querySelector('video');
function handleMove(e) {
// code here
}
speed.addEventListener('mousemove', handleMove);
div.speed 的位置首先從 speed.offsetHeight 可以取得 speed 的元素高度,並透過 MouseEvent.offsetY 取得在 speed 的當前位置。
也就是說當 MouseEvent.offsetY 除以 speed.offsetHeight 就會是當前位置的比例了!
function handleMove(e) {
const percent = e.offsetY / this.offsetHeight; // this 是 speed
}
div.speed-bar 的 height 屬性由於在 CSS 中設定 speedBar 高度我們要使用百分比,所以要先將剛剛算出的 percent 轉成百分比並設定在 speedBar 的高度
function handleMove(e) {
const percent = e.offsetY / this.offsetHeight;
const height = Math.round(percent * 100);
speedBar.style.height = height + '%';
}
這裡用的方法是將 percent 乘以 100 再做四捨五入,並套用至 speedBar 的 CSS
設定播放速度是我卡關較多的地方,一開始我無法理解要如何設定最小值為 0.4、最大值 4。
目前已有的 percent 值從 0 到 1 之間,若要設定成 0.4~4 的區間,要算一下數學
function handleMove(e) {
const percent = e.offsetY / this.offsetHeight;
const height = Math.round(percent * 100);
const min = 0.4; // 最小值
const max = 4; // 最大值
const playbackRate = (max - min) * percent + min;
speedBar.style.height = height + '%';
}
如此計算就可以將 playbackRate 的區間設定在 0.4~4 之間了
div.speed-bar 的 textContent、設定 video 得播放速度(playbackRate)最後就是設定影片播放速度以及 speedBar 的 textContent 了!
function handleMove(e) {
const percent = e.offsetY / this.offsetHeight;
const height = Math.round(percent * 100);
const min = 0.4; // 最小值
const max = 4; // 最大值
const playbackRate = (max - min) * percent + min;
speedBar.style.height = height + '%';
speedBar.textContent = playbackRate.toFixed(2) + 'x';
video.playbackRate = playbackRate;
}
speedBar.textContent 由於希望數字能最多在小數點後 2 位,故使用 toFixed(..)
到這裡我們就完成今天的作品了!